package com.cl.master.config;

import com.cl.master.domain.Admin;
import com.cl.master.service.impl.AdminServiceImpl;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author xc
 * @Date 2023/3/27 23:06
 * @Version 1.0
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    AdminServiceImpl adminService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了==授权");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("！执行了认证操作！");
        /*强制转换类型为UsernamePasswordToken*/
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        /**
         * 1、根据已获得的秘钥返回的的用户名查找数据库中的对应管理员表
         * 2、如果存在管理员，登录成功
         * 3、否则失败
         * Shiro登录流程简记：用户点击登录，把用户名和密码传到后台，
         * 最终会执行到MyRealm里面，它是通过用户名到数据库里面查找是否有这个实体，
         * 查到一个实体后，将它与用户输入的信息做比较，匹配失败控制台会报错的，也即是验证失败
         */
        Admin admin = adminService.getAdminByUsername(token.getUsername());
        if (admin==null){
            return null;
        }
        return new SimpleAuthenticationInfo("",admin.getPassword(),"");
    }
}
